package com.crrcdt.vue_project.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.tree.Tree;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crrcdt.vue_project.entity.Manager;
import com.crrcdt.vue_project.entity.Permission;
import com.crrcdt.vue_project.entity.PermissionApi;
import com.crrcdt.vue_project.entity.Role;
import com.crrcdt.vue_project.result.Result;
import com.crrcdt.vue_project.result.ResultFactory;
import com.crrcdt.vue_project.service.PermissionApiService;
import com.crrcdt.vue_project.service.PermissionService;
import com.crrcdt.vue_project.service.RoleService;
import com.crrcdt.vue_project.util.TreeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lj on 2020/10/22.
 * @version 1.0
 */
@RestController
@RequestMapping(value = "/api/private/v1")
@Slf4j
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private PermissionApiService permissionApiService;
    // 角色列表
    @GetMapping("/roles")
    public Result getRoles() {
        final List<Role> roles = roleService.list(null);
        if(roles==null){
            return ResultFactory.buildFailResult("获取失败！");
        }
        roles.stream().forEach(role -> {
            final String[] ids = role.getPsIds().split(",");
            final List<Permission> permissions = permissionService.list(new QueryWrapper<Permission>().in("ps_id", ids));
            // 添加path值
            permissions.stream().forEach(entity->{
                final Integer psId = entity.getPsId();
                final List<PermissionApi> permissionApis = permissionApiService.list(new QueryWrapper<PermissionApi>().eq("ps_id", psId));
                Assert.notEmpty(permissionApis,"permissionApis不能为空");
                entity.setPath(permissionApis.get(0).getPsApiPath());
            });
            final List<Tree<String>> treeList = TreeUtils.getTrees(permissions);
            role.setChildren(treeList);
        });
        return ResultFactory.buildSuccessResult(roles, "获取成功");
    }
    //添加角色
    @PostMapping("/roles")
    public Result addRoles(@RequestBody Role role) {
        final boolean res = roleService.save(role);
        if(res){
            return ResultFactory.buildSuccessResult(role, "创建成功");
        }
        return ResultFactory.buildFailResult("创建失败");
    }
    //根据 ID 查询角色
    @GetMapping("/roles/{roleId}")
    public Result getRoleById(@PathVariable("roleId") int id) {
        final Role role = roleService.getById(id);
        if(role!=null){
            return ResultFactory.buildSuccessResult(role, "查询成功");
        }
        return ResultFactory.buildFailResult("查询失败");
    }
    //编辑提交角色
    @PutMapping("/roles/{id}")
    public Result updateRole(@PathVariable("id") int id,@RequestBody Role role) {
        role.setRoleId(id);
        final boolean res = roleService.updateById(role);
        if(res){
            final Role roleNew = roleService.getById(id);
            return ResultFactory.buildSuccessResult(roleNew, "编辑成功");
        }
        return ResultFactory.buildFailResult("编辑失败");
    }
    //删除角色
    @DeleteMapping("/roles/{id}")
    public Result deleteRole(@PathVariable("id") int id) {
        final boolean res = roleService.removeById(id);
        if(res){
            return ResultFactory.buildSuccessResult(null, "删除成功");
        }
        return ResultFactory.buildFailResult("删除失败");
    }
    // 角色授权
    @PostMapping("/roles/{roleId}/rights")
    public Result grantRoleAuthor(@PathVariable("roleId") int roleId, @RequestBody Role role) {
        role.setRoleId(roleId);
        role.setPsIds(role.getRids());
        final boolean res = roleService.updateById(role);
        if(res){
            return ResultFactory.buildSuccessResult(null, "更新成功");
        }
        return ResultFactory.buildFailResult("更新失败");
    }
    //删除角色指定权限
    @DeleteMapping("/roles/{roleId}/rights/{rightId}")
    public Result deleteRoleAuthor(@PathVariable("roleId") int roleId,@PathVariable("rightId") int rightId) {
        final Role role = roleService.getById(roleId);
        final String[] ids = role.getPsIds().split(",");
        final List<String> idsNew = Arrays.asList(ids).stream().filter(id -> !StringUtils.equals(id,rightId+"")).collect(Collectors.toList());
        final String idsRes = StringUtils.join(idsNew, ",");
        final Role updateRole = new Role();
        updateRole.setRoleId(roleId);
        updateRole.setPsIds(idsRes);
        final boolean res = roleService.updateById(updateRole);
        if(res){
            final Role roleNew = roleService.getById(roleId);
            final String updateIds = roleNew.getPsIds();
            final List<Permission> permissions = permissionService.list(new QueryWrapper<Permission>().in("ps_id", updateIds.split(",")));
            permissions.stream().forEach(entity->{
                final List<PermissionApi> permissionApis = permissionApiService.list(new QueryWrapper<PermissionApi>().eq("ps_id", entity.getPsId()));
                Assert.notEmpty(permissionApis,"permissionApis不能为空！");
                entity.setPath(permissionApis.get(0).getPsApiPath());
            });
            final List<Tree<String>> treeList = TreeUtils.getTrees(permissions);
            return ResultFactory.buildSuccessResult(treeList, "取消权限成功");
        }
        return ResultFactory.buildFailResult("取消权限失败");
    }
}
